﻿using System;
using K9Nano.Caching;
using K9Nano.Dependency;

namespace K9Nano.Admin.Weixin.OAuth
{
    public interface IWeixinTokenCodeCache
    {
        string CreateCode(WeixinTokenCode tokenCode);

        WeixinTokenCode Get(string code);
    }

    [Serializable]
    public class WeixinTokenCode
    {
        public string ClientId { get; set; }

        public string OpenId { get; set; }

        public string UnionId { get; set; }

        public string AppId { get; set; }
    }

    internal class WeixinTokenCodeCache : IWeixinTokenCodeCache, ISingletonDependency
    {
        private readonly ITypedCache<WeixinTokenCode> _cache;

        public WeixinTokenCodeCache(ITypedCache<WeixinTokenCode> cache)
        {
            _cache = cache;
        }


        public string CreateCode(WeixinTokenCode tokenCode)
        {
            var code = Guid.NewGuid().ToString("N");
            _cache.Put(code, tokenCode, TimeSpan.FromMinutes(5));
            return code;
        }

        public WeixinTokenCode Get(string code)
        {
            var tokenCode = _cache.Get(code);
            if (tokenCode != null)
            {
                _cache.Remove(code); // 只能获取一次
            }

            return tokenCode;
        }
    }
}